<?php
/**
 * This file is part of the Yacms (http://www.yacms.org)
 * Copyright (c) 2019 gylr0505 (http://www.yacms.org)
 *
 * Author: 鬼一浪人 <gylr0505@163.com>
 *
 * DateTime: 19-10-24 下午11:48
 * Description:
 */
 
declare(strict_types = 1);

namespace App\Template;

class Checker
{
    const ERROR_CODE_STATUS = [
        '0'      => 'success',
        '40037'  => 'template_id不正确',
        '41028'  => 'form_id不正确，或者过期',
        '41029'  => 'form_id已被使用',
        '41030'  => 'page不正确',
        '45009'  => '接口调用超过限额',
        //下列为自定义错误
        '400'    => '返回值解析失败',
        '40001'  => 'access_token不正确',
        '40004'  => '接收者（用户）的 openid不可为空',
        '40005'  => '发送消息不可为空',
        '40006'  => '请求的url不可为空'
    ];

    /**
     * @var int 发送消息返回的错误码，默认使用自定义错误码
     */
    protected $error_code = 400;

    /**
     * @var string 错误信息，无错误为空
     */
    protected $error_msg = '';

    public function __construct($back_result = null)
    {
        if ($back_result){
            $this->parseResult($back_result);
        }
    }

    /**
     * 解析发出请求返回的值，做最后的验证
     * @param $back_result
     * @return void|null
     */
    public function parseResult($back_result)
    {
        try{
            $result = [];
            if(is_string($back_result)){
                $result = json_decode($back_result, true);
            }
            //表示无数据，便不处理
            if (!$result){
                $this->error_code = 400;
                $this->error_msg = self::ERROR_CODE_STATUS['400'];
                return;
            }
            $this->error_code = $result['errcode'] ?? 0;
            $this->error_msg  = $result['errmsg'] ?? '';

        } catch (\InvalidArgumentException $e)
        {
            //有任何错误，不处理
            return null;
        }
    }

    /**
     * 检测参数，必传参数检测
     *
     * @param array $params
     * @return bool
     * @throws \Exception
     */
    public function checkParams($params = [])
    {
        if (!isset($params['template_id']) || $params['template_id'] == ''){
            throw new \Exception(self::ERROR_CODE_STATUS['40037'],40037);
        }
        if (!isset($params['form_id']) || $params['form_id'] == ''){
            throw new \Exception(self::ERROR_CODE_STATUS['41028'],41028);
        }
        if (!isset($params['access_token']) || $params['access_token'] == ''){
            throw new \Exception(self::ERROR_CODE_STATUS['40001'],40001);
        }
        if (!isset($params['touser']) || $params['touser'] == ''){
            throw new \Exception(self::ERROR_CODE_STATUS['40004'],40004);
        }
        if (!isset($params['data']) || !$params['data']){
            throw new \Exception(self::ERROR_CODE_STATUS['40005'],40005);
        }
        if (!isset($params['template_id']) || $params['template_id'] == ''){
            throw new \Exception(self::ERROR_CODE_STATUS['40006'],40006);
        }
        return true;
    }

    /**
     * 是否发送成功
     * @return bool
     */
    public function isSuccess()
    {
        return ($this->error_code <=> 0) === 0;
    }

    public function getErrorCode()
    {
        $this->error_code;
    }

    public function getErrorMsg()
    {
        return $this->error_msg;
    }

    /**
     * @return bool
     */
    public function isError()
    {
        $msg = trim($this->error_msg);
        return isset($msg['0']) && $msg != '' && !$this->isSuccess();
    }
}